

//
//  TMhometableview.swift
//  GZWeibo007
//
//  Created by myd on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD
class TMhometableview: UITableView {
    
    var delega : chilkinbutton?
    var status : CZStatus?
        {
        didSet
        {
            self.chilkloadup()
        }
    }
    var frist = true
    var coments = [TMComments]()
    var counts = 0 {
        didSet
        {self.view.count = counts
            
        }}
    var zan = 0
    var zhuanfa = 0
    let view = homehandview()
    
    let ReuseIdentifier = "ReuseIdentifier"
    
    
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: UITableViewStyle.Grouped)
        setview()
        self.infiniteScrollingView
        //        print("comment:\(coments)")
        self.delegate = self
        self.dataSource = self
        self.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreStatus()
        }
        
        
    }
    
  
    //上拉
    func loadMoreStatus() {
        let since_id = 0
        let max_id = self.coments.last?.id ?? 0
        
        TMComments.loadComment(since_id, max_id: max_id, id: status!.id, finished: { (coments, error, total_number, previous_cursor, next_cursor) -> () in
            self.infiniteScrollingView.stopAnimating()
            if coments == nil || error != nil
            {
                SVProgressHUD.showErrorWithStatus("加载错误")
                return
            }
            
            self.coments += coments! as [TMComments]
            self.reloadData()
            if self.counts == 0 {
                self.counts = total_number}
        })
    }
    
    //点击
    func chilkloadup() {
        var max_id = 0
        var since_id = self.coments.first?.id ?? 0
        max_id = 0
        if frist == false{
            let load = TMComments(dict: nil)
            load.load = true
            self.coments.insert(load, atIndex: 0)
            self.reloadData()
        }
        
        
        
        
        
        TMComments.loadComment(since_id, max_id: max_id, id: status!.id, finished: { (coments, error, total_number, previous_cursor, next_cursor) -> () in
            if self.frist == true
            {
                
                self.frist = false
                self.reloadData()
                return
            }
            self.coments.removeFirst()
            if coments == nil || error != nil
            {
                self.reloadData()
                SVProgressHUD.showErrorWithStatus("加载错误")
                self.reloadData()
                return
            }
            
            self.counts = total_number
            self.coments = coments! as [TMComments] + self.coments
            self.reloadData()
            
        })
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setview()
    {
        self.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        // 注册转发cell
        self.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusForwardCell.rawValue)
        self.registerClass(TMCommentCell.self, forCellReuseIdentifier: ReuseIdentifier)
        self.registerClass(TMnothing.self, forCellReuseIdentifier: "nothing")
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1
        {
            view.delegate = self
            return view
        }
        return nil
    }
    
}
extension TMhometableview : UITableViewDelegate,UITableViewDataSource,chilkloadup
{
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //        print("heightForRowAtIndexPath: \(indexPath)")
        // 根据不同的模型,计算出cell的高度
        // 1.获取模型
        
        if indexPath.section == 1
        {
            if self.coments.count == 0 || self.counts == 0
            {
                return 60
            }
            let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier) as! TMCommentCell
            let comm = self.coments[indexPath.item]
            if comm.load == true
            {
                return 60
            }
            cell.comments =  self.coments[indexPath.item]
            
            return cell.cellhright
        }
        // 2.查看模型是否有缓存的行高,如果有缓存的行高直接返回
        if status?.rowHeight != nil {
            // 有缓存的行高
            //            print("返回缓存行高: \(status.rowHeight)")
            return (status?.rowHeight!)!
        }
        
        // 没有缓存行高
        // 3.获取cell(需要根据不同的模型,获取对应的cell),使用不带IndexPath方法
        let cellID = status!.cellID()
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! CZStatusCell
        
        let rowHeight = cell.rowHeight(status!)
        
        // 5.保存计算好的行高
        status!.rowHeight = rowHeight
        
        return rowHeight
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        if indexPath.section == 0 {
            
            let cell =  tableView.dequeueReusableCellWithIdentifier(status!.cellID(), forIndexPath: indexPath) as! CZStatusCell
            cell.status = status
//            zanButton
//            转发
//            forwardButton
//            //评论
//            commentButton
            cell.bottomView.pinglun = self.counts
            cell.delegate = self
            return cell
            
        }
        
        if self.coments.count == 0
        {
            let cell = tableView.dequeueReusableCellWithIdentifier("nothing") as! TMnothing
            cell.num = self.counts
            return cell
        }
        let tmmodel = self.coments[indexPath.item]
        if tmmodel.load == true
        {
            return  TMloging()
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier, forIndexPath: indexPath)as! TMCommentCell
        cell.comments = tmmodel
        return cell
        
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0{
            return 1
        }
        
        return self.coments.count == 0 ? 1 : self.coments.count
        
        
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1
        {
            return 20
        }
        
        return 8
    }
}
protocol chilkloadup : NSObjectProtocol
{
    func chilkloadup()
}
class homehandview : UIView {
    var count = 0
        {
        didSet
        {
            button.setTitle("评论\(count)", forState: UIControlState.Normal)
        }
    }
    var delegate : chilkloadup?
    private  let button = UIButton()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setview()
    }
    func setview()
    {
        
        addSubview(button)
        button.setTitle("评论\(0)", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
        button.addTarget(self, action: "chilk", forControlEvents: UIControlEvents.TouchUpInside)
        button.titleLabel?.font = UIFont.systemFontOfSize(11)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        button.frame = CGRectMake(0, 0, 50, self.bounds.height)
    }
    func chilk()
    {
        delegate?.chilkloadup()
    }
}
//点击评论按钮
protocol chilkinbutton : NSObjectProtocol
{
    func chilkin(status : CZStatus)
}
extension TMhometableview : chileinbutton
{
    
    func chinkinbutton(status : CZStatus)
    {
        delega?.chilkin(self.status!.retweeted_status!)
    }
    func jumpclick(titlestr: String, status: CZStatus) {
        self.jumpclick(titlestr, status: status)
    }
}

